import { Inject, Injectable } from '@nestjs/common'
import { RedisClientType } from 'redis'

@Injectable()
export class RedisService {
   @Inject('REDIS_CLIENT')
   private redisClient: RedisClientType

   async addPositions(key: string, positionName: string, position: [number, number]) {
      await this.redisClient.geoAdd(key, {
         longitude: position[0],
         latitude: position[1],
         member: positionName
      })
   }

   async getPosition(key: string, positionName: string) {
      const res = await this.redisClient.geoPos(key, positionName)
      return {
         name: positionName,
         longitude: res[0].longitude,
         latitude: res[0].latitude
      }
   }

   async getPositionList(key: string) {
      const positions = await this.redisClient.zRange(key, 0, -1)

      const list = []
      for (let i = 0; i < positions.length; i++) {
         const res = await this.getPosition(key, positions[i])
         list.push(res)
      }

      return list
   }

   async getNearbyPositions(key: string, position: [number, number], radius: number) {
      const positionNameList = await this.redisClient.geoRadius(
         key,
         {
            longitude: position[0],
            latitude: position[1]
         },
         radius,
         'km'
      )

      const list = []
      for (let i = 0; i < positionNameList.length; i++) {
         const res = await this.getPosition(key, positionNameList[i])
         list.push(res)
      }

      return { data: list, statusCode: 200 }
   }
}
